// pages/myProfile/myProfile.js
import { getUserInfoApi, updateUserInfoApi } from '../../api/user'
import { baseURL } from '../../utils/config'
import { setUserInfo, getUserInfo } from '../../utils/user'
import { areaList } from '@vant/area-data'
import { isMobile, isEmail } from '../../utils/validate'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    genderText: '',
    company: '',
    gender: 0,
    headImg: '',
    nickName: '',
    phone: '',
    delegateUnitAddress: '',
    delegateUnitArea: '',
    delegateUnitCity: '',
    delegateUnitName: '',
    delegateUnitProvince: '',
    email: '',
    payUnitAddress: '',
    userName: '',
    genderShow: false,
    actions: [{ name: '男' }, { name: '女' }],
    areaList,
    areaValue: '',
    areaShow: false
  },

  getGenderText() {
    const gender = this.data.gender
    return Number(gender) === 1 ? '男' : Number(gender) === 2 ? '女' : ''
  },
  onClickGender() {
    this.setData({
      genderShow: true
    })
  },

  onClose() {
    this.setData({ genderShow: false })
  },

  onSelect(event) {
    console.log(event.detail)
    this.setData(
      {
        genderText: event.detail.name,
        gender: event.detail.name === '男' ? 1 : 2
      },
      () => {
        this.updateUserInfo()
      }
    )
  },

  async getUserInfo() {
    const [err, userInfo] = await getUserInfoApi()
    if (err) return
    const {
      company,
      delegateUnitAddress,
      delegateUnitArea,
      delegateUnitCity,
      delegateUnitName,
      delegateUnitProvince,
      email,
      gender,
      headImg,
      nickName,
      payUnitAddress,
      phone,
      userName
    } = userInfo
    this.setData(
      {
        company,
        delegateUnitAddress,
        delegateUnitArea,
        delegateUnitCity,
        delegateUnitName,
        delegateUnitProvince,
        email,
        gender,
        headImg,
        nickName,
        payUnitAddress,
        phone,
        userName
      },
      () => {
        this.setData({
          genderText: this.getGenderText()
        })
        this.getAreaValue()
      }
    )
  },

  getAreaValue() {
    const area = this.data.delegateUnitArea
    let areaValue = ''
    for (const key in areaList.county_list) {
      if (Object.hasOwnProperty.call(areaList.county_list, key)) {
        const value = areaList.county_list[key]
        if (value === area) {
          areaValue = key
          break
        }
      }
    }
    this.setData({
      areaValue
    })
  },

  async updateUserInfo() {
    const {
      company,
      delegateUnitAddress,
      delegateUnitArea,
      delegateUnitCity,
      delegateUnitName,
      delegateUnitProvince,
      email,
      gender,
      headImg,
      nickName,
      payUnitAddress,
      phone,
      userName
    } = this.data

    if (phone.trim().length > 0 && !isMobile(phone)) {
      wx.showToast({
        title: '手机号格式验证失败',
        icon: 'none'
      })
      return
    }

    if (email.trim().length > 0 && !isEmail(email)) {
      wx.showToast({
        title: '邮箱格式验证失败',
        icon: 'none'
      })
      return
    }

    const userInfo = {
      company,
      delegateUnitAddress,
      delegateUnitArea,
      delegateUnitCity,
      delegateUnitName,
      delegateUnitProvince,
      email,
      gender,
      headImg,
      nickName,
      payUnitAddress,
      phone,
      userName
    }
    const [err] = await updateUserInfoApi(userInfo)
    if (err) return
    const info = getUserInfo()
    setUserInfo({
      ...info,
      ...userInfo
    })
    wx.showToast({
      title: '保存成功',
      icon: 'none'
    })
  },

  onBurl(e) {
    this.updateUserInfo()
  },

  afterRead(event) {
    const { file } = event.detail
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.showLoading({
      title: '上传中'
    })
    wx.uploadFile({
      url: `${baseURL}api/common/upload/oss/img`,
      filePath: file.url,
      name: 'file',
      formData: { user: 'test' },
      success: (res) => {
        const { statusCode, data: resData } = res
        if (statusCode !== 200) {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
          return
        }
        const { code, data, msg } = JSON.parse(resData)

        if (code !== 200) {
          wx.showToast({
            title: `${code}-${msg}`,
            icon: 'none'
          })
        }

        this.setData(
          {
            headImg: `${data.osshost}${data.image}`
          },
          () => {
            this.updateUserInfo()
          }
        )
      },
      complete: () => {
        wx.hideToast()
      }
    })
  },

  areaConfirm(e) {
    const value = e.detail.values
    this.setData(
      {
        areaValue: value[2].code,
        delegateUnitProvince: value[0].name,
        delegateUnitCity: value[1].name,
        delegateUnitArea: value[2].name,
        areaShow: false
      },
      () => {
        this.updateUserInfo()
      }
    )
  },

  areaCancel() {
    const instance = this.selectComponent('.area')
    instance.reset(this.data.areaValue)
    this.setData({
      areaShow: false
    })
  },

  showArea() {
    this.setData({
      areaShow: true
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // this.getUserInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
